﻿using System.Web.Mvc;
using System.Web.Routing;
using NOSDC.Models;
using System.Web.Security;
using NOSDC.Pocos;
using NOSDC.Services;
using System;
using NOSDC.Utility;

namespace NOSDC.Controllers
{
    public class AccountController : Controller
    {
        public IFormsAuthenticationService FormsService { get; set; }
        public IMembershipService MembershipService { get; set; }
        private readonly IAccountService _service;

        public AccountController()
        {
            _service = new AccountService();
        }

        protected override void Initialize(RequestContext requestContext)
        {
            if (FormsService == null)
            {
                FormsService = new FormsAuthenticationService();
            }
            if (MembershipService == null)
            {
                MembershipService = new AccountMembershipService();
            }

            base.Initialize(requestContext);
        }

        public ActionResult Login()
        {
            return View();
        }

        public ActionResult Forgot()
        {
            return View();
        }

        [HttpPost]
        public ActionResult Forgot(ForgotViewModel model)
        {
            if (ModelState.IsValid)
            {
                var recovery = new PasswordRecovery
                                   {
                                       Email = model.Email,
                                       UserIP = Utility.Helper.GetIPAddress()
                                   };

                recovery = _service.CreateRecoveryRequest(recovery);
                Mail.SendRecoveryEmail(model.Email, recovery.LinkGenerated);


                return RedirectToAction("RecoveryEmailSent");
            }

            return View(model);
        }

        public ActionResult RecoverPassword(Guid? token)
        {
            if (token == null || token == Guid.Empty) return RedirectToAction("Index", "Home");

            if (_service.ValidateRecovery(token.Value, DateTime.Now))
            {
                return View(new ResetPassword {Token = token});
            }

            return RedirectToAction("Http500", "Error");
        }

        [HttpPost]
        public ActionResult RecoverPassword(ResetPassword reset)
        {
            if (reset.Token == null || reset.Token == Guid.Empty) return RedirectToAction("Index", "Home");

            if (_service.ValidateRecovery(reset.Token.Value, DateTime.Now))
            {
                if (ModelState.IsValid)
                {
                    MembershipService.UpdatePassword(_service.RecoveryRequestEmail(reset.Token.Value), reset.Password);
                    _service.UserHasRecovered(reset.Token.Value);
                }
                else
                {
                    return View(reset);
                }
            }

            return RedirectToAction("PasswordUpdated", "Account");
        }

        public ActionResult PasswordUpdated()
        {
            return View();
        }

        public ActionResult RecoveryEmailSent()
        {
            return View();
        }

        [HttpPost]
        public ActionResult Login(LogOnModel model, string returnUrl)
        {
            if (ModelState.IsValid)
            {
                if (MembershipService.ValidateUser(model.UserName, model.Password))
                {
                    FormsService.SignIn(model.UserName, model.RememberMe);
                    FormsAuthentication.SetAuthCookie(model.UserName, model.RememberMe);
                    if (Url.IsLocalUrl(returnUrl))
                    {
                        return Redirect(returnUrl);
                    }

                    return RedirectToAction("Index", "Home");
                }

                ModelState.AddModelError("", "The user name or password provided is incorrect.");
            }

            return View(model);
        }

        public ActionResult LogOff()
        {
            FormsService.SignOut();

            return RedirectToAction("Index", "Home");
        }

        public ActionResult Register()
        {
            ViewBag.PasswordLength = MembershipService.MinPasswordLength;
            return View();
        }

        [HttpPost]
        public ActionResult Register(RegisterModel model)
        {
            if (ModelState.IsValid)
            {
                // Attempt to register the user
                var createStatus = MembershipService.CreateUser(model);

                if (createStatus == MembershipCreateStatus.Success)
                {
                    FormsService.SignIn(model.UserName, false);
                    return RedirectToAction("Index", "Home");
                }
                
                ModelState.AddModelError("", AccountValidation.ErrorCodeToString(createStatus));
            }

            ViewBag.PasswordLength = MembershipService.MinPasswordLength;
            return View(model);
        }

        // **************************************
        // URL: /Account/ChangePassword
        // **************************************

        //[Authorize]
        //public ActionResult ChangePassword()
        //{
        //    ViewBag.PasswordLength = MembershipService.MinPasswordLength;
        //    return View();
        //}

        //[Authorize]
        //[HttpPost]
        //public ActionResult ChangePassword(ChangePasswordModel model)
        //{
        //    if (ModelState.IsValid)
        //    {
        //        if (MembershipService.ChangePassword(User.Identity.Name, model.OldPassword, model.NewPassword))
        //        {
        //            return RedirectToAction("ChangePasswordSuccess");
        //        }
        //        else
        //        {
        //            ModelState.AddModelError("", "The current password is incorrect or the new password is invalid.");
        //        }
        //    }

        //    // If we got this far, something failed, redisplay form
        //    ViewBag.PasswordLength = MembershipService.MinPasswordLength;
        //    return View(model);
        //}

        // **************************************
        // URL: /Account/ChangePasswordSuccess
        // **************************************

        //public ActionResult ChangePasswordSuccess()
        //{
        //    return View();
        //}
    }
}
